package mark.tom.friend.view.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.SwitchCompat;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;

import javax.inject.Inject;

import io.reactivex.Observable;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
import mark.tom.friend.app.CustomApplication;
import mark.tom.friend.base.activity.BaseActivity;
import mark.tom.friend.base.util.RxViewUtil;
import mark.tom.friend.base.util.SystemUtil;
import mark.tom.friend.bean.bo.AppConfigBO;
import mark.tom.friend.bean.vo.AppInfoVO;
import mark.tom.friend.component.DaggerAppInfoComponent;
import mark.tom.friend.consts.ActivityRouterConsts;
import mark.tom.friend.consts.BundleKeyConsts;
import mark.tom.friend.contract.AppInfoContract;
import mark.tom.friend.module.AppInfoModule;
import mark.tom.friend.presenter.AppInfoPresenter;
import mark.tom.friend.roll.R;

import static mark.tom.friend.consts.BundleKeyConsts.APP_CONFIG_GROUP_EXTRA;
import static mark.tom.friend.consts.BundleKeyConsts.APP_CONFIG_GROUP_SERVER;
import static mark.tom.friend.consts.BundleKeyConsts.BUNDLE_KEY_APP_CONFIG_CONTENT;
import static mark.tom.friend.consts.BundleKeyConsts.BUNDLE_KEY_APP_CONFIG_GROUP;
import static mark.tom.friend.consts.BundleKeyConsts.BUNDLE_KEY_APP_NAME;
import static mark.tom.friend.consts.BundleKeyConsts.BUNDLE_KEY_APP_PACKAGE_NAME;
import static mark.tom.friend.presenter.AppInfoPresenter.REQUEST_CODE_EXTRA_CONFIG;
import static mark.tom.friend.presenter.AppInfoPresenter.REQUEST_CODE_SERVER_CONFIG;

@Route(path = ActivityRouterConsts.ROUTER_APP_INFO)
public class AppInfoActivity extends BaseActivity implements AppInfoContract.View {

    @Autowired Toolbar appToolBar;
    @Autowired SwitchCompat appDebugSwitchCompat;
    @Autowired TextView appPackageNameTextView, appVersionNameTextView, appMd5TextView, appSha1TextView;
    @Autowired TextView appDebugTextView, appServerTextView, appExtraTextView;

    @Autowired(innerWired = true) @Inject AppInfoPresenter mPresenter;

    @Override
    protected int getLayoutId() {
        return R.layout.layout_app_setting;
    }

    @Override
    protected void onCreate(View contentView, Bundle savedInstanceState) {
        DaggerAppInfoComponent.builder()
                .appComponent(CustomApplication.get(this).getAppComponent())
                .appInfoModule(new AppInfoModule(this))
                .build()
                .inject(this);
        // 使用路由框架初始化
        ARouter.getInstance().inject(this, mPresenter, contentView, savedInstanceState);
        // 设置toolbar
        setToolBar(appToolBar);
        // 绑定控件事件
        bindViewListener();
        // 初始化显示数据
        mPresenter.onStart();
    }

    private void bindViewListener() {
        // 设置开关按钮切换监听
        appDebugSwitchCompat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                updateAppDebugAbleStatue(isChecked);
            }
        });
        Consumer<View> consumer = new Consumer<View>() {
            @SuppressLint("CheckResult")
            @Override
            public void accept(@NonNull View view) {
                final int requestCode;
                final String groupName;
                switch (view.getId()) {
                    case R.id.appServerTextView: {
                        groupName = APP_CONFIG_GROUP_SERVER;
                        requestCode = REQUEST_CODE_SERVER_CONFIG;
                        break;
                    }
                    case R.id.appExtraTextView: {
                        groupName = APP_CONFIG_GROUP_EXTRA;
                        requestCode = REQUEST_CODE_EXTRA_CONFIG;
                        break;
                    }
                    default: {
                        groupName = null;
                        requestCode = 0;
                        break;
                    }
                }
                if (null != groupName) {
                    mPresenter.directToConfigPage(groupName)
                            .compose(AppInfoActivity.this.<AppConfigBO>bindToLifecycle())
                            .subscribe(new Consumer<AppConfigBO>() {
                                @Override
                                public void accept(@NonNull AppConfigBO content) {
                                    String cacheContent;
                                    if (APP_CONFIG_GROUP_SERVER.equals(groupName)) {
                                        cacheContent = content.getServerConfig();
                                    } else {
                                        cacheContent = content.getExtraConfig();
                                    }
                                    directToConfigPage(requestCode, groupName, cacheContent);
                                }
                            });
                }
            }
        };
        // 设置服务器设置按钮点击监听
        RxViewUtil.bindViewClickListener(appServerTextView, bindToLifecycle(), consumer);
        // 设置额外设置按钮点击监听
        RxViewUtil.bindViewClickListener(appExtraTextView, bindToLifecycle(), consumer);
    }

    @SuppressLint("CheckResult")
    private void updateAppDebugAbleStatue(boolean isChecked) {
        // 保存状态到数据库
        mPresenter.updateAppDebugAbleStatus(isChecked)
                .compose(this.<Boolean>bindToLifecycle())
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(@NonNull Boolean isChecked) {
                        // 控制其他元素enable状态
                        setAppDebugViewByStatus(isChecked);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(@NonNull Throwable throwable) {
                        // 发生异常则还原状态
                        appDebugSwitchCompat.setChecked(false);
                    }
                });
    }

    @SuppressLint("CheckResult")
    @Override
    public void showAppConfigInfo(AppInfoVO appInfo) {
        // 设置应用基本信息
        appToolBar.setTitle(appInfo.getAppName());
        appPackageNameTextView.setText(appInfo.getPackageName());
        appVersionNameTextView.setText(appInfo.getVersionName());
        appMd5TextView.setText(appInfo.getMd5Fingerprint());
        appSha1TextView.setText(appInfo.getSha1Fingerprint());
        // 加载应用配置信息
        mPresenter.loadAppDebugInfo()
                .compose(this.<AppConfigBO>bindToLifecycle())
                .subscribe(new Consumer<AppConfigBO>() {
                    @Override
                    public void accept(@NonNull AppConfigBO appSettingBO) {
                        setAppDebugViewByStatus(appSettingBO.isDebugAble());
                    }
                });
    }

    @Override
    public void directToConfigPage(int requestCode, @BundleKeyConsts.AppConfigGroup String group, String content) {
        ARouter.getInstance()
                .build(ActivityRouterConsts.ROUTER_APP_CONFIG)
                .withString(BUNDLE_KEY_APP_NAME, appToolBar.getTitle().toString())
                .withString(BUNDLE_KEY_APP_PACKAGE_NAME, appPackageNameTextView.getText().toString())
                .withString(BUNDLE_KEY_APP_CONFIG_GROUP, group)
                .withString(BUNDLE_KEY_APP_CONFIG_CONTENT, content)
                .direction(this, requestCode);
    }

    private void setAppDebugViewByStatus(boolean debugAble) {
        // 设置开关是否打开
        appDebugSwitchCompat.setChecked(debugAble);
        appDebugTextView.setEnabled(debugAble);
        appServerTextView.setEnabled(debugAble);
        appExtraTextView.setEnabled(debugAble);
        int serverTextDrawLeftRes = debugAble ? R.mipmap.icon_title_server_enable : R.mipmap.icon_title_server_unenable;
        appServerTextView.setCompoundDrawablesWithIntrinsicBounds(serverTextDrawLeftRes, 0, 0, 0);
        int extraTextDrawLeftRes = debugAble ? R.mipmap.icon_title_extra_enable : R.mipmap.icon_title_extra_unenable;
        appExtraTextView.setCompoundDrawablesWithIntrinsicBounds(extraTextDrawLeftRes, 0, 0, 0);
        int textColorRes = debugAble ? R.color.colorPrimaryDark : android.R.color.darker_gray;
        appServerTextView.setTextColor(SystemUtil.getColorByRes(getResources(), textColorRes));
        appExtraTextView.setTextColor(SystemUtil.getColorByRes(getResources(), textColorRes));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && null != data) {
            Observable<String> result = mPresenter.onResult(requestCode, data.getStringExtra(BUNDLE_KEY_APP_CONFIG_CONTENT));
            if (null != result) {
                result.compose(this.<String>bindToLifecycle()).subscribe();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mPresenter.onDestroy();
    }

}
